package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.qo.BpmnInfoQueryObject;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }

    @Override
    public String upload(MultipartFile file) throws IOException {
        String extension = FileUploadUtils.getExtension(file);
        if (!"bpmn".equals(extension)) {
            throw new BusinessException("请选择bpmn文件");
        }
        String path = FileUploadUtils.upload(SystemConfig.getProfile(), file);
        return path;
    }

    @Override
    public void deploy(String path, String info, String bpmnType) throws IOException {
        // 部署流程定义 获得部署对象
        FileInputStream inputStream = new FileInputStream(new File(SystemConfig.getProfile(), path));
        Deployment deployment = repositoryService.createDeployment().
                addInputStream(path, inputStream).
                deploy();
        // 获得流程定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(deployment.getId()).
                singleResult();
        inputStream.close();

        // 保存业务表信息
        BpmnInfo bpmnInfo = new BpmnInfo();
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setInfo(info);
        bpmnInfo.setDeploymentId(deployment.getId());
        bpmnInfo.setDeployTime(deployment.getDeploymentTime());

        bpmnInfoMapper.insert(bpmnInfo);
    }

    @Override
    public Integer delete(Long id) {

        BpmnInfo bpmnInfo = bpmnInfoMapper.selectOne(id);
        // 获得定义对象
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(bpmnInfo.getDeploymentId()).
                singleResult();

        // 通过流程定义的 key 获得该流程定义下的所有流程实例
        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().
                processDefinitionKey(bpmnInfo.getActProcessKey()).
                list();
        // 如果有流程实例存在 则需要完成全部流程实例才能删除
        if (list.size() != 0) {
            if (processDefinition.isSuspended()){
                return null;
            }
            repositoryService.suspendProcessDefinitionById(processDefinition.getId());
            return null;
        }

        // 删除业务表数据
        bpmnInfoMapper.delete(id);

        // 删除流程定义
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);

        // 删除定义文件
        File file = new File(SystemConfig.getProfile(), processDefinition.getResourceName());
        if (file != null) {
            file.delete();
        }
        return 1;
    }

    @Override
    public void readResource(String deploymentId, String type, HttpServletResponse resp) throws IOException {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(deploymentId).
                singleResult();
        InputStream inputStream = null;
        if ("xml".equals(type)) {
            inputStream = repositoryService.getResourceAsStream(deploymentId, processDefinition.getResourceName());
        }else {
            DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator();
            /**
             * 第一个参数: bpmnModel 信息
             * 第二个参数: 高亮点节点信息
             * 第三个参数: 高亮连线集合
             */
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            inputStream = defaultProcessDiagramGenerator.
                    generateDiagram(bpmnModel, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                            "楷体","楷体","楷体");
        }

        IOUtils.copy(inputStream,resp.getOutputStream());
    }

    @Override
    public List<BpmnInfo> getByBpmnType(String type) {
        return bpmnInfoMapper.getByBpmnType(type);
    }

}
